﻿namespace Chameleon.Samples
{
	using Chameleon.Data;
	using System.Data.Entity;

	/// <summary>
	/// Entity Framework code-first data context.
	/// </summary>
	
	public sealed class EntityContext : DbContext
	{
		/// <summary>
		/// Indicates that the CodeFirstEntity is part of the code-first mapping.
		/// </summary>
		
		internal DbSet<BasicEntity> Entities { get; set; }


		/// <summary>
		/// Performs fluent mapping of entities.
		/// </summary>
		/// <param name="modelBuilder">The builder that defines the model for the context being created.</param>

		protected override void OnModelCreating( DbModelBuilder modelBuilder )
		{
			// map the BasicEntity to the table dbo.BasicEntity
			modelBuilder.Entity<BasicEntity>().ToTable( "dbo.BasicEntity" );
		}


		/// <summary>
		/// Initializes a new instance to use the specified connection string.
		/// </summary>
		/// <param name="connection">
		/// Must be in the form "name=myname" and the name must be found in the config file or an exception will be thrown.
		/// <para>See remarks for specifics.</para>
		/// </param>
		/// <remarks>
		/// From the DbContext remarks:
		/// The [connection] can also be passed in the form "name=myname", in which case the name must be found in 
		/// the config file or an exception will be thrown. Note that the connection found in the app.config or 
		/// web.config file can be a normal database connection string (not a special Entity Framework connection 
		/// string) in which case the DbContext will use Code First. However, if the connection found in the config 
		/// file is a special Entity Framework connection string, then the DbContext will use Database/Model First 
		/// and the model specified in the connection string will be used.
		/// </remarks>
		
		internal EntityContext( string connection ) : base( connection ) {}


		/// <summary>
		/// Config file key that contains the connection string.
		/// </summary>
		
		const string Connection = "name=EntitySample";


		/// <summary>
		/// Creates and returns a new depository based on this context type using the defined connection string.
		/// </summary>
		
		public static IDepository Depository()
		{
			return new EntityDepository( () => new EntityContext( Connection ) );
		}
	}
}
